package com.cloudbroker.bsc.common.search.elasticsearch;

import com.cloudbroker.bcs.common.configure.ConfigUtil;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ES 搜所引擎
 *
 * @create 2016-6-11
 * @author moyin18602
 * @version
 */
public abstract class AbstractElasticsearch {
	private static String ELASTICSEARCH_HOST;
	private static String ELASTICSEARCH_URL;
	private static String ELASTICSEARCH_CLUSTER;
	private static int ELASTICSEARCH_POST;
	private static TransportClient client;

	AbstractElasticsearch() {
		// 获取对应的配置集
		ELASTICSEARCH_HOST = ConfigUtil.get("searchEngine.elasticsearch.host","localhost:9300");
		ELASTICSEARCH_CLUSTER = ConfigUtil.get("searchEngine.elasticsearch.cluster","my-application");
		
//		String[] host = ELASTICSEARCH_HOST.split(":");
//		if (host.length > 1) {
//			ELASTICSEARCH_URL = host[0];
//			ELASTICSEARCH_POST = Integer.parseInt(host[1]);
//		} else {
//			ELASTICSEARCH_URL = host[0];
//			ELASTICSEARCH_POST = 9300;
//		}
	}

	/**
	 * @return
	 * @throws UnknownHostException
	 */
	public Client getClient() throws UnknownHostException {
		if (client == null) {
			synchronized (AbstractElasticsearch.class) {
				if (client == null) {
					Settings settings = Settings.settingsBuilder().put("cluster.name", ELASTICSEARCH_CLUSTER)
						.put("client.transport.sniff", true).build();
					
					try {
						System.out.println(ELASTICSEARCH_HOST);
						client = TransportClient.builder().settings(settings).build();
						String [] clusterHostArray=ELASTICSEARCH_HOST.split(",");
						for(String hostName : clusterHostArray){
							String  ip=hostName.split(":")[0];
							Integer port=Integer.valueOf(hostName.split(":")[1]);
							client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip),Integer.valueOf(port)));
						}
					
					} catch (UnknownHostException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return client;
	}
}
